import React, { Component } from 'react'
import { Descriptions, Button, Select, Avatar, List, Pagination, Image, Modal, Form, Input, TimePicker, Steps, Divider, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import moment from 'moment';
import Order from '@/Public/Order'
import { mallOrderConfig } from '@/Public/Order/orderConfigs'
import { selectedOrderData } from '@/Redux/ActionTypes/public/BaseTable/publicActionCreator'
import { history } from '@/index'
import { managerBorderOfficialThunk, queryShipAddressIdThunk, managerUpdateOrderStatusThunk, getExpressOnPassageThunk } from './ActionCreators'
import "./index.css"

const expressStatus = { 0: '未寄件', 1: '未揽件', 2: '已揽件', 3: '已收货' }

const { Option } = Select
const { TextArea } = Input
const { Step } = Steps;

const mapStateToProps = (state) => ({
  selectedOrderData: state.baseTable.selectedOrderData
})

const mapDispatchToProps = (dispatch) => ({
  managerBorderOfficial: (...rest) => dispatch(managerBorderOfficialThunk(...rest)),
  queryShipAddressId: (...rest) => dispatch(queryShipAddressIdThunk(...rest)),
  managerUpdateOrderStatus: (...rest) => dispatch(managerUpdateOrderStatusThunk(...rest)),
  setSelectedOrderData: (...rest) => dispatch(selectedOrderData(...rest)),
  getExpressOnPassage: (...rest) => dispatch(getExpressOnPassageThunk(...rest))
})
@connect(mapStateToProps, mapDispatchToProps)
class OrderMessage extends Component {

  state = {
    isModalVisible: false,
    expressNode: '',// 快递单号
    isOrderMessage: true,
    expressData: {},// 物流信息
  }

  formRef = React.createRef(this);

  showModal = () => {
    this.setState({
      isModalVisible: true
    }, () => {
      const { selectedOrderData } = this.props
      this.formRef && this.formRef.current?.setFieldsValue(selectedOrderData)
    })
  };

  // 确认发货
  handleOk = (data) => {
    const { managerBorderOfficial, managerUpdateOrderStatus, selectedOrderData, setSelectedOrderData } = this.props
    this.setState({
      isModalVisible: false
    })
    let sendData = Object.assign({}, data)
    sendData.pickupStartTime = moment(data.pickupStartTime[0]?.format("HH:mm"))._i
    sendData.pickupEndTime = moment(data.pickupStartTime[1]?.format("HH:mm"))._i
    this.setState({
      isOrderMessa: true
    })
    managerBorderOfficial(sendData).then(res => {
      if (res.data.success) {
        const expressNode = res.data.data.split('：')[1]
        message.success(res.data.message)
        this.setState({
          expressNode
        })
        selectedOrderData.expressStatus = 1
        setSelectedOrderData(selectedOrderData)
        // 修改订单状态
        // managerUpdateOrderStatus(selectedOrderData.orderId, 3)
      } else {
        message.error(res, data.message)
      }
    })
  };

  handleCancel = () => {
    this.setState({
      isModalVisible: false
    })
  };

  componentDidMount() {
    const { selectedOrderData, queryShipAddressId, getExpressOnPassage } = this.props
    queryShipAddressId().then(res => {
      selectedOrderData.addressId = res.data.data
    })
    this.formRef && this.formRef.current?.setFieldsValue(selectedOrderData)

    getExpressOnPassage(selectedOrderData.orderId).then(res => {
      if (res.data.data) {
        this.setState({
          expressData: res.data.data
        })
      }
    })
  }


  reverse = (arr) => { //定义翻转函数
    var newarr = [];//建立一个新的空数组，用来存放翻转数据
    for (var i = arr.length - 1; i >= 0; i--) {//遍历输入的数组
      newarr[newarr.length] = arr[i]; //将旧数组索引下的值翻转给新数组
    }
    return newarr;//返回新数组的值
  }


  render() {
    const { selectedOrderData } = this.props
    const { expressData } = this.state
    let resultList = []
    if (expressData.resultList) {
      resultList = this.reverse(expressData.resultList)
    }
    const bookList = selectedOrderData?.bookList
    return (
      <div>
        <ArrowLeftOutlined
          style={{
            fontSize: '20px',
            height: '40px',
            transform: 'translate(0,10px)',
            fontWeight: 'bold',
            cursor: 'pointer'
          }}
          onClick={() => {
            history.go(-1)
          }}
        />
        <Order
          key={Math.random()}
          orderConfig={mallOrderConfig}
          selectedOrderData={selectedOrderData}
          isOrderMessage={true}
        />
        {/* 订单信息 */}
        <div className="goods-info" style={{
          height: `${bookList.length * 120 + 250}px`
        }}>
          {
            bookList.map(item => {
              return (
                <div style={{
                  position: 'relative',
                  height: '120px'
                }}
                  key={item.id}>
                  <Image
                    width={100}
                    src={item.url}
                  />
                  <h3 style={{ position: 'absolute', top: '0', left: '170px', fontWeight: '700' }}>{item.title}</h3>
                  <div style={{ position: 'absolute', top: '30px', left: '172px', fontSize: '13px', color: 'rgb(144, 147, 153)' }}>{item.writer}</div>
                  <div style={{ position: 'absolute', top: '30px', left: '222px', fontSize: '13px', color: 'rgb(144, 147, 153)' }}>{item.publisher}</div>
                  <div style={{ position: 'absolute', top: '60px', left: '172px', fontSize: '18px', color: 'rgb(255, 72, 72)' }}>{"￥ " + item.fee}</div>
                  <div style={{ position: 'absolute', top: '20px', right: '50px', fontSize: '22px', color: 'rgb(0,0,0)', fontWeight: '600' }}>{"×" + item.num}</div>
                </div>
              )
            })
          }
          <div className="total-box">
            <div style={{ position: 'absolute', top: '3px', right: '110px', fontSize: '18px', color: 'rgb(0,0,0)', fontWeight: '600' }}>运费：</div>
            <div style={{ position: 'absolute', right: '50px', fontSize: '20px', color: 'rgb(0,0,0)', fontWeight: '600' }}><span style={{ color: 'rgb(123, 97, 255)' }}>{selectedOrderData.freight}</span> 元</div>
            <div style={{ position: 'absolute', top: '40px', right: '50px', fontSize: '18px', color: 'rgb(0,0,0)', fontWeight: '600' }}>总计：<span style={{ color: 'rgb(255, 72, 72)' }}>{"￥ " + selectedOrderData.total}</span></div>
          </div>
        </div>
        {/* 物流信息 */}
        <div className="express-info">
          <div className="express-info-title">物流信息</div>
          <Button type="primary"
            onClick={this.showModal}
            disabled={
              (selectedOrderData.orderStatus === '2' && selectedOrderData.expressStatus === 0) ? false : true
            }
          >发货</Button>
          {
            resultList.length > 0 && <div>
              <div className="orderId">快递单号：{expressData.nu}</div>
              <Steps progressDot current={resultList.length - 1} direction="vertical" style={{ position: 'relative', top: '30px', left: '40px' }}>
                {
                  resultList.map(item => {
                    return <Step title={item.context} description={item.time} />
                  })
                }
              </Steps>
            </div>
          }
          <Modal title="发货" footer={null} cancelButtonProps={true} centered={true} okText="发货" className="sendGoodsModal" visible={this.state.isModalVisible} onCancel={this.handleCancel} style={{ width: '700px' }}>
            <Form
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={{ remember: true }}
              onFinish={this.handleOk}
              ref={this.formRef}
              // onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="发货地址ID"
                name="addressId"
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="订单ID"
                name="orderId"
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="选择快递"
                name="expressCompany"
                rules={[{ required: true }]}
              >
                <Select placeholder="请选择快递类型">
                  <Option value="shunfeng">顺丰快递</Option>
                  <Option value="shentong">申通快递</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="物品重量"
                name="weight"
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="预约日期"
                name="dayType"
                rules={[{ required: true }]}
              >
                <Select placeholder="请选择预约日期">
                  <Option value="今天">今天</Option>
                  <Option value="明天">明天</Option>
                  <Option value="后天">后天</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="上门时间"
                name="pickupStartTime"
                rules={[{ required: true }]}
              >
                <TimePicker.RangePicker />
              </Form.Item>
              <Form.Item
                label="备注"
                name="remark"
              >
                <TextArea rows={4} />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="default" onClick={this.handleCancel} style={{ transform: "translate(50px,0)" }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit" style={{ transform: "translate(70px,0)" }}>
                  发货
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </div>
        {/* 退货物流 */}
        {/* <div className="return-express-info">
          <div className="return-express-info-title">退货物流信息</div>
          <div className="orderId">快递单号：</div>
          <Steps progressDot current={1} direction="vertical" style={{ position: 'relative', top: '30px', left: '40px' }}>
            {
              resultList.map(item => {
                return <Step title={item.context} description={item.time} />
              })
            }
            <Step title="已发货" description="This is a description. This is a description." />
            <Step title="已揽件" description="This is a description. This is a description." />
            <Step title="已派送" description="This is a description. This is a description." />
            <Step title="已运输" description="This is a description." />
            <Step title="已签收" description="This is a description." />
          </Steps>
          <Button style={{ borderRadius: '7px', height: '40px', width: '110px', color: '#fff', backgroundColor: 'rgb(64, 158, 255)', marginTop: '60px' }}>确认退款</Button>
        </div> */}

      </div>
    )
  }
}

export default OrderMessage
